<?php

// Last Modified: $Id: user_auth_fns.php 211 2005-09-28 23:58:19Z denk $

require_once('db_fns.php');

function register($values, $attendee_id = "")
// register new person with db
// return true or error message
{
	extract($values);
	// connect to db
	$conn = db_connect();
	if (!$conn)
		return 'Could not connect to database server - please try later.';
	//encrypt their password.
	$salt = rand_ascii(2);
	$crypt_pass = crypt("$password", $salt);
//	$crypt_pass = crypt("$password"); # let salt be generated
	//If we are not updating an already existing record do this section.
	if ($values['update'] != 'Y') {
		// check if username is unique 
		$result = pg_query("select * from attendee where username='$username'"); 
		if (!$result) return 'Could not execute query';
		if (pg_num_rows($result)>0) 
			return '<p><span class="redtext">That username is taken you can try our <a href="forgot_passwd.php">forgot password</a> form or choose another one.</span></p><br />';
		$result = pg_query("select * from attendee where email_addr='$email_addr'"); 
		if (!$result) return 'Could not execute query';
		if (pg_num_rows($result)>0) 
			return '<p><span class="redtext">That email address is already in our databse perhaps you <a href="forgot_passwd.php">forgot your password</a>?</span></p><br />';
		// if ok, put in db
		$query="INSERT INTO attendee (first_name, last_name, organization, nickname, address1, address2, city, state, zip, areacode, phone3, phone4, password, email_addr, created, username, contact, partner_contact, others_viewing, country) VALUES ('$first_name', '$last_name', '$organization', '$nickname', '$address1', '$address2', '$city', '$state', '$zip', '$areacode', '$phone3', '$phone4',  '$crypt_pass', '$email_addr', '$timestamp', '$username',  '$contact', '$partner_contact', '$others_viewing', '$country')";
		$result = pg_query("$query");
		if (!$result)
			return "Could not register you  in database - please try again later.";
		}
	//If we are updating an already exisitng record do this section.
	if ($values['update'] == 'Y' && (empty($attendee_id) || !isset($attendee_id)))
		return "We could not update your personal information because we could not determine your attendee ID.<br />\n";
	if ($values['update'] == 'Y') {
		$query = "UPDATE attendee SET first_name = '$first_name', last_name = '$last_name', organization = '$organization', nickname = '$nickname', address1 = '$address1', address2 = '$address2', city = '$city', state = '$state', zip = '$zip', areacode = '$areacode', phone3 = '$phone3', phone4 = '$phone4', email_addr = '$email_addr', modified = '$timestamp', contact = '$contact', partner_contact = '$partner_contact', others_viewing = '$others_viewing', country = '$country' WHERE attendee_id = '$attendee_id'";
		$result = pg_query("$query");
		if (!$result)
			return "Could not update your personal info in database - please try again later.";
		}
	//If this user was added through the admin interface we want to go right to thier schedule so determine the attendee_id of the just generated record and return that value.
	if ($values['admin_add_user'] == 'Y') {
		$entered_id = sql_last_inserted_id($result, attendee, attendee_id);
		insert_con_registration($entered_id, $event_day, $reg_type, $reg_cost, approved, $_SESSION['attendee_id']);
		return $entered_id;
		}
	//otherwise return true.
	return true;
}
 
function create_user_name($username) {
	$conn = db_connect();
	$query = "SELECT attendee_id FROM attendee WHERE username ~~* '$username'";
	$result = pg_query("$query");
	if (pg_numrows($result) == '0')
		return $username;
	$final = 8000;
	for ( $i = 1; $i <= $final ; $i++) {
		$testusername = $username.$i;
		$query = "SELECT attendee_id FROM attendee WHERE username ~~* '$testusername'";
		$result = pg_query("$query");
		if (pg_numrows($result) == '0') $final = $i;
		}
	return $testusername;
}

function login($username, $input_password) {
	// check username and password with db

	// connect to db
	$username = strtolower($username);
	$conn = db_connect();
	if (!$conn)
		return false;

	// Get password and attendee_id from database
	$result = pg_query("SELECT password, attendee_id FROM attendee 
                         WHERE username='$username'");
	if (pg_num_rows($result) == 0) {
		return 'no_username';
		}
	if (pg_num_rows($result) > 1) {
		return 'too_many_username';
		}
	//now that we know we have one record to deal with do the following
	$password = pg_fetch_result($result,0,"password");
	if (crypt($input_password,$password) != $password) {
		return 'wrong_password';
		}
	//Process record that was returned, set session variables
	if (crypt($input_password,$password) == $password) {
		$attendee_id = pg_fetch_result($result,0,"attendee_id");
		$values = get_user_info($attendee_id);
		$username = $values['username'];
		$admin = $values['admin'];
		$last_login = $values['last_loginepoch'];
		$_SESSION['attendee_id'] = $attendee_id;
		$_SESSION['current_attendee_id'] = $attendee_id;
		$_SESSION['username'] = $username;
		$_SESSION['admin'] = $admin;
		$_SESSION['last_login'] = $last_login;
		//Set last_login time to the current time.
		$query = "UPDATE attendee SET last_login = 'now()' WHERE attendee_id = '$attendee_id'";
		pg_query("$query");
		return true;
		}
	else 
		return false;
}

function check_valid_user()
// see if somebody is logged in and return false if they are not
{
  if (isset($_SESSION['username']) && isset($_SESSION['attendee_id']) && $_SESSION['attendee_id']!="0" && $_SESSION['attendee_id']!="")
    return true;
  else
  {
     return false;
  }  
}

function get_user_info($attendee_id)
{
  //first we get their info
    // connect to db
  $conn = db_connect();
  if (!$conn)
    return false;
  $result = (pg_query("SELECT attendee.*, EXTRACT(EPOCH FROM attendee.last_login) as last_loginepoch, EXTRACT(EPOCH FROM attendee.modified) as modifiedepoch, EXTRACT(EPOCH FROM attendee.created) as createdepoch, EXTRACT(EPOCH FROM checked_in) as checked_inepoch FROM attendee, con_reg WHERE attendee.attendee_id = '$attendee_id' AND con_reg.attendee_id = attendee.attendee_id"));
	if (pg_numrows($result) == '0') {
		$result = (pg_query("SELECT attendee.*, EXTRACT(EPOCH FROM attendee.last_login) as last_loginepoch, EXTRACT(EPOCH FROM attendee.modified) as modifiedepoch, EXTRACT(EPOCH FROM attendee.created) as createdepoch FROM attendee WHERE attendee.attendee_id = '$attendee_id'"));
		$values = pg_fetch_array($result, 0, PGSQL_ASSOC) ;
		return $values;
		}
  
  $values = pg_fetch_array($result, 0, PGSQL_ASSOC) ;
  return $values;
}

function rand_ascii($length = 1) {
    //better_srand();
    srand((double) microtime() * 1000000);

    $s = "";
    for ($i = 1; $i <= $length; $i++) {
        $s .= chr(rand(40, 126)); // return only typeable 7 bit ascii, avoid quote marks
    }
    return $s;
 }
 
function generate_password($digits,$c,$st)
{
//$digits = amount of chars the password should have (between 3 and 29)
//$c = if true, I,i,L,l will be changed to 1 and O or o will be changed to 0 (Zero) to prevent mistakes by an userinput
//$st = string to "U" = upper, "L" = lower, null=casesensitive
//example call $password=generate_password(6,true,null);
	if(!ereg("^([4-9]|((1|2){1}[0-9]{1}))$",$digits)) // 3-29 chars allowed
		$digits=4;
	for(;;) {
		$pwd=null; $o=null;
		// Generates the password ....
		for ($x=0;$x<$digits;) {
			$y = rand(1,1000); 
			if($y>350 && $y<601) $d=chr(rand(48,57));
			if($y<351) $d=chr(rand(65,90));
			if($y>600) $d=chr(rand(97,122));
			if($d!=$o) {                  
				$o=$d; $pwd.=$d; $x++;
				}
			}
		// if you want that the user will not be confused by O or 0 ("Oh" or "Null")
		// or 1 or l ("One" or "L"), set $c=true;
		if($c) {
			$pwd=eregi_replace("(l|i)","1",$pwd);
			$pwd=eregi_replace("(o)","0",$pwd);
			}
		// If the PW fits your purpose (e.g. this regexpression) return it, else make a new one
		// (You can change this regular-expression how you want ....)
		if(ereg("^[a-zA-Z]{1}([a-zA-Z]+[0-9][a-zA-Z]+)+",$pwd))
			break;
		}
	if($st=="L") $pwd=strtolower($pwd);
	if($st=="U") $pwd=strtoupper($pwd);
	return $pwd;
}

function reset_password($username, $email_addr)
// set password for username to a random value
// return the new password or false on failure
{ 

	$new_password = generate_password(8,true,null);
	//encrypt their password.
	$salt = rand_ascii(2);
	$crypt_pass = crypt("$new_password", $salt);
//	$crypt_pass = crypt("$new_password"); # let salt be generated
  // set user's password to this in database or return false
  if (!($conn = db_connect()))
      return false;
  $result = pg_query( "UPDATE attendee
                          SET password = '$crypt_pass'
                          WHERE username = '$username' AND email_addr =
                          '$email_addr'");
  if (!$result)
    return false;  // not changed
  else
    return $new_password;  // changed successfully  
}

function update_password($attendee_id, $password) { 
// set password to crypt of given value
	//generate 2 character salt to make this a standard DES encrypted password
	$salt = rand_ascii(2);
	$crypt_pass = crypt("$password", $salt);
//	$crypt_pass = crypt("$password"); # let salt be generated
  // set user's password to this in database or return false
  if (!($conn = db_connect()))
      return false;
  $result = pg_query( "UPDATE attendee
                          SET password = '$crypt_pass'
                          WHERE attendee_id = '$attendee_id'");
  if (!$result)
    return false;  // not changed
  else
    return true;  // changed successfully  
}

function notify_password($username, $password)
// notify the user that their password has been changed
{
    if (!($conn = db_connect()))
      return false;
    $result = pg_query("SELECT email_addr FROM attendee
                            WHERE username='$username'");
    if (!$result)
    {
      return false;  // not changed
    }
    elseif (pg_num_rows($result)==0)
    {
      return false; // username not in db
    }
    else
    {
      $email = pg_result($result, 0, 'email_addr');
      $from = "From: UNY-Con <registration@uny-con.com>";
      $mesg = "Your UNY-Con http://loki.local/~plummer/uny-con/registration/login.php password has been changed:

Username: $username
Password: $password

Please change it next time you log in.";


      if (mail($email, 'UNY-Con login information', $mesg, $from))
        return true;      
      else
        return false;     
    }
} 

function get_attendees($search_key, $search_string, $sortkey="last_name", $sortdir="ASC") {
	//this function returns an array of all attendee info we can find.
	if (!db_connect())
		return false;
	if ($sortkey == 'last_name') {
		$sortkey = "last_name $sortdir, first_name $sortdir";
		$sortdir = "";
		}
	if ($sortkey == 'first_name') {
		$sortkey = "first_name $sortdir, last_name $sortdir";
		$sortdir = "";
		}
	if ($sortkey != 'last_name') $sortby = "$sortkey $sortdir, last_name ASC";
		$query = "SELECT *, EXTRACT(EPOCH FROM last_login) as last_loginepoch, EXTRACT(EPOCH FROM modified) as modifiedepoch, EXTRACT(EPOCH FROM created) as createdepoch FROM attendee WHERE $search_key ~~* '$search_string' ORDER BY $sortby";
	$result = pg_query("$query");
	$attendee_result_array = db_result_to_array($result);
	return $attendee_result_array;
}
?>
